<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>实验时遇到的bug - 读论文</title>


        <!-- Custom HTML head -->
        
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="favicon.svg">
        <link rel="shortcut icon" href="favicon.png">
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        <link rel="stylesheet" href="css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->

        <!-- MathJax -->
        <script async type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded affix "><a href="chapter_1.html">读论文活动</a></li><li class="chapter-item expanded affix "><li class="part-title">6.824 分布式系统</li><li class="chapter-item expanded "><a href="Mapreduce.html"><strong aria-hidden="true">1.</strong> Mapreduce</a></li><li class="chapter-item expanded "><a href="GFS.html"><strong aria-hidden="true">2.</strong> GFS</a></li><li class="chapter-item expanded "><a href="VM-FT.html"><strong aria-hidden="true">3.</strong> VM-FT</a></li><li class="chapter-item expanded "><a href="Raft.html"><strong aria-hidden="true">4.</strong> Raft</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="Raft0.html"><strong aria-hidden="true">4.1.</strong> 感性认识Raft</a></li><li class="chapter-item expanded "><a href="Raft1.html"><strong aria-hidden="true">4.2.</strong> 什么是Raft？</a></li><li class="chapter-item expanded "><a href="Raft2.html"><strong aria-hidden="true">4.3.</strong> 复制状态机（Replicated State Machine）</a></li><li class="chapter-item expanded "><a href="Raft3.html"><strong aria-hidden="true">4.4.</strong> What's wrong with Paxos?</a></li><li class="chapter-item expanded "><a href="Raft4.html"><strong aria-hidden="true">4.5.</strong> 向可理解性进军</a></li><li class="chapter-item expanded "><a href="Raft5.html"><strong aria-hidden="true">4.6.</strong> Raft共识算法（零）</a></li><li class="chapter-item expanded "><a href="Raft6.html"><strong aria-hidden="true">4.7.</strong> Raft共识算法（一）——基础概念</a></li><li class="chapter-item expanded "><a href="Raft7.html"><strong aria-hidden="true">4.8.</strong> Raft共识算法（二）——选举leader</a></li><li class="chapter-item expanded "><a href="Raft8.html"><strong aria-hidden="true">4.9.</strong> Raft共识算法（三）——日志备份（log replication）</a></li><li class="chapter-item expanded "><a href="Raft9.html"><strong aria-hidden="true">4.10.</strong> Raft共识算法（四）——安全性和选举限制</a></li><li class="chapter-item expanded "><a href="Raft10.html"><strong aria-hidden="true">4.11.</strong> Raft共识算法（五）——如何提交之前term里的entry</a></li><li class="chapter-item expanded "><a href="Raft11.html"><strong aria-hidden="true">4.12.</strong> Raft共识算法（六）——安全性定理</a></li><li class="chapter-item expanded "><a href="Raft12.html"><strong aria-hidden="true">4.13.</strong> Raft共识算法（七）——如果follower/candidate宕机了</a></li><li class="chapter-item expanded "><a href="Raft13.html"><strong aria-hidden="true">4.14.</strong> Raft共识算法（八）——时间与可用性</a></li><li class="chapter-item expanded "><a href="Raft14.html"><strong aria-hidden="true">4.15.</strong> 成员变更</a></li><li class="chapter-item expanded "><a href="Raft15.html"><strong aria-hidden="true">4.16.</strong> 日志压缩</a></li><li class="chapter-item expanded "><a href="Raft16.html"><strong aria-hidden="true">4.17.</strong> 与Client的交互</a></li><li class="chapter-item expanded "><a href="Raft17.html" class="active"><strong aria-hidden="true">4.18.</strong> 实验时遇到的bug</a></li><li class="chapter-item expanded "><a href="Raft18.html"><strong aria-hidden="true">4.19.</strong> 总结</a></li></ol></li><li class="chapter-item expanded "><a href="Zookeeper.html"><strong aria-hidden="true">5.</strong> Zookeeper</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="linearizability1.html"><strong aria-hidden="true">5.1.</strong> 线性一致性（一）——基础概念</a></li><li class="chapter-item expanded "><a href="linearizability2.html"><strong aria-hidden="true">5.2.</strong> 线性一致性（二）——细究linearizability</a></li><li class="chapter-item expanded "><a href="zk_intro.html"><strong aria-hidden="true">5.3.</strong> 引言</a></li><li class="chapter-item expanded "><a href="zk_service.html"><strong aria-hidden="true">5.4.</strong> Zookeeper Service</a></li><li class="chapter-item expanded "><a href="zk_api.html"><strong aria-hidden="true">5.5.</strong> Zookeeper API</a></li><li class="chapter-item expanded "><a href="zk_prop.html"><strong aria-hidden="true">5.6.</strong> Zookeeper的性质</a></li><li class="chapter-item expanded "><a href="zk_ex.html"><strong aria-hidden="true">5.7.</strong> 基于Zookeeper实现锁</a></li></ol></li><li class="chapter-item expanded "><a href="CRAQ.html"><strong aria-hidden="true">6.</strong> CRAQ</a></li><li class="chapter-item expanded "><a href="lamport_clock.html"><strong aria-hidden="true">7.</strong> Time, Clocks, and the Ordering of Events in a Distributed System</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="lamport_clock1.html"><strong aria-hidden="true">7.1.</strong> 引言</a></li><li class="chapter-item expanded "><a href="lamport_clock_partial_order.html"><strong aria-hidden="true">7.2.</strong> 偏序关系</a></li><li class="chapter-item expanded "><a href="lamport_logic_clock.html"><strong aria-hidden="true">7.3.</strong> 逻辑时钟</a></li><li class="chapter-item expanded "><a href="lamport_total_order.html"><strong aria-hidden="true">7.4.</strong> 全序关系</a></li><li class="chapter-item expanded "><a href="lamport_clock_ana_behave.html"><strong aria-hidden="true">7.5.</strong> 异常事件</a></li><li class="chapter-item expanded "><a href="lamport_p_clock.html"><strong aria-hidden="true">7.6.</strong> 物理时钟</a></li><li class="chapter-item expanded "><a href="lamport_end.html"><strong aria-hidden="true">7.7.</strong> 结论</a></li></ol></li><li class="chapter-item expanded "><li class="part-title">6.828 操作系统</li><li class="chapter-item expanded "><a href="828intro.html"><strong aria-hidden="true">8.</strong> Killer of Microseconds</a></li><li class="chapter-item expanded "><a href="cloudlab.html"><strong aria-hidden="true">9.</strong> CloudLab</a></li><li class="chapter-item expanded "><a href="dpdk.html"><strong aria-hidden="true">10.</strong> DPDK</a></li><li class="chapter-item expanded "><a href="spdk.html"><strong aria-hidden="true">11.</strong> SPDK</a></li><li class="chapter-item expanded "><a href="Shenango.html"><strong aria-hidden="true">12.</strong> Shenango</a></li><li class="chapter-item expanded "><a href="TritonSort.html"><strong aria-hidden="true">13.</strong> TritonSort</a></li><li class="chapter-item expanded "><a href="Profiling.html"><strong aria-hidden="true">14.</strong> Profiling a warehouse-scale computer</a></li><li class="chapter-item expanded affix "><li class="part-title">6.828 - Network</li><li class="chapter-item expanded affix "><li class="part-title">CS244 - Advanced Topics in Networking</li><li class="chapter-item expanded "><a href="DARPA_NET.html"><strong aria-hidden="true">15.</strong> The Design Philosophy of The DARPA Internet Protocols</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="DARPA_NET2.html"><strong aria-hidden="true">15.1.</strong> Second Level Goals</a></li><li class="chapter-item expanded "><a href="DARPA_NET3.html"><strong aria-hidden="true">15.2.</strong> Types of Service</a></li><li class="chapter-item expanded "><a href="DARPA_NET4.html"><strong aria-hidden="true">15.3.</strong> Varieties of Networks</a></li><li class="chapter-item expanded "><a href="DARPA_NET5.html"><strong aria-hidden="true">15.4.</strong> Architecture and Implementation</a></li><li class="chapter-item expanded "><a href="DARPA_NET6.html"><strong aria-hidden="true">15.5.</strong> Datagrams</a></li></ol></li><li class="chapter-item expanded "><li class="part-title">最后</li><li class="chapter-item expanded "><a href="end.html"><strong aria-hidden="true">16.</strong> 最后</a></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">读论文</h1>

                    <div class="right-buttons">
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="实验时遇到的bug"><a class="header" href="#实验时遇到的bug">实验时遇到的bug</a></h1>
<h3 id="隐晦的死锁问题"><a class="header" href="#隐晦的死锁问题">隐晦的死锁问题</a></h3>
<p><img src="./assets/raft_e9.png" alt="raft_e9" /></p>
<p>在for循环里面，cond获取到了锁，但是接下来for循环的条件不成立，于是函数在持有锁的情况下退出。</p>
<p>解决方法：for循环结束之后将锁释放掉。</p>
<blockquote>
<p>这个bug超级隐晦。我甚至一度以为mit给的测试脚本有bug，不过到最后发现，原来还是自己的问题。<br />
或者我写了一个量子程序，因为bug出现之后，当我加了几行打印语句之后再运行，测试程序又没bug了。<br />
并发程序真的太难写了！
可能rust更适合写并发程序吧，毕竟在rust里，锁是有生命周期的，过了它的生命周期，锁可以自动被释放。</p>
</blockquote>
<h3 id="乱序的网络请求"><a class="header" href="#乱序的网络请求">乱序的网络请求</a></h3>
<p>刚实现完lab2b的时候，每跑100遍就fail一次，找了一天。</p>
<p align="center"><img width="60%" src="assets/raft_e10.jpeg" alt="raft_e10" /></p>
<p>发现是follower会收到leader过期的AppendEntries请求，这个请求有之前提交过的entry，然后follower响应这个过期的请求，根据图中的第三条规则，就把自己的entry给删掉了一部分。</p>
<p>当这种网络请求被乱序接收后，follower没有保证幂等。</p>
<p>我通过给每个网络请求加一个SeqId，然后才发现的这个问题。</p>
<p><img src="./assets/raft_seq.png" alt="raft_seq" /></p>
<p>查看guide发现，Q&amp;A（https://thesquareplanet.com/blog/raft-qa/）里有一个一模一样的问题，回答如下</p>
<blockquote>
<p><strong>Note that the rule starts with “if an existing entry conflicts”.</strong><br />
即如果有冲突的话，再进行delete操作。这样的话哪怕收到过期请求，也能够保证幂等了。</p>
</blockquote>
<h3 id="我的程序有点慢"><a class="header" href="#我的程序有点慢">我的程序有点慢</a></h3>
<p>网上的大佬说用go的channel来做这个实验会更优雅。于是我一开始使用go的channel进行多线程之间的同步。</p>
<p>但是由于太会使，导致go的协程一直阻塞在channel上，并不会被系统回收。随着程序运行的越久，无法被回收协程就越多，最终程序变得越来越慢。</p>
<p>网上称这个问题为&quot;go routine泄漏&quot;。</p>
<p>后来把channel相关的代码全部删除，使用更熟悉的lock/mutex来实现论文里的全部逻辑。才通过测试。</p>
<p>当然熟悉go channel的大佬可以忽略这条。</p>
<h3 id="记得go-test--race"><a class="header" href="#记得go-test--race">记得go test -race</a></h3>
<p>一个Raft节点并行运行的任务非常的多，所以一旦发生数据竞争的问题，程序必出bug。</p>
<p>解决方法就是上一把大锁，只有获取这个大锁的协程才能读取/修改Raft节点里的状态。</p>
<p>一定要保证自己的程序可以通过go test -race的测试，否则发现测试程序fail之后，debug半天然后发现是由于数据竞争导致的，那就得不偿失了。</p>
<h3 id="活锁问题"><a class="header" href="#活锁问题">活锁问题</a></h3>
<blockquote>
<p>根据<a href="https://thesquareplanet.com/blog/students-guide-to-raft/">guide</a><br />
Make sure you reset your election timer <strong>exactly</strong> when Figure 2 says you should.<br />
Specifically, you should <strong>only</strong> restart your election timer if</p>
<p>a) you get an AppendEntries RPC from the <strong>current</strong> leader (i.e., if the term in the AppendEntries arguments is outdated, you should <strong>not</strong> reset your timer);</p>
<p>b) you are starting an election;</p>
<p>c) you <strong>grant</strong> a vote to another peer.</p>
</blockquote>
<p>Guide里说只有三种情况才会重置server的选举定时器。</p>
<p>原因是如果在lab2b的日志复制模块里，加上选举限制之后，有资格成为leader的server会变少。</p>
<p>因此如果这个server的选举定时器一直被重置的话，则它没有机会成为leader。</p>
<p>如此一来会造成“活锁”。<strong>活锁的意思是，所有server都在工作，但是系统do not make any progress。</strong></p>
<h3 id="快照策略给raft引入了巨大的复杂性"><a class="header" href="#快照策略给raft引入了巨大的复杂性">快照策略给raft引入了巨大的复杂性</a></h3>
<p>因为加入快照策略后，被快照的日志条目就索引不到了。</p>
<p>因此raft节点的状态需要引入额外的三个变量：</p>
<ul>
<li><strong>lastIncludedLogIndex</strong>: for servers to update</li>
<li><strong>lastIncludedTerm</strong>: term of lastIncludedCommandIndex</li>
<li><strong>lastIncludedCommandIndex</strong>: the snapshot replaces all entries up through and including this index</li>
</ul>
<p>并且重新修改论文中图2的逻辑，仔细地处理边界情况。</p>
<p>老师在lecture里说，他不太懂InstallSnapshot RPC的规则6说的是啥意思，他可能觉得如果收到了很老的InstallSnapshot请求，那直接丢弃就好了。我觉得也是。</p>
<h3 id="处理client请求"><a class="header" href="#处理client请求">处理client请求</a></h3>
<p>如果client的发过来的命令太久没有提交，则超过一个timeout之后，直接返回命令执行成功。<br />
要不然没法通过测试。</p>
<p>甚至网上也有大佬在leader收到client的command就立即返回true。<br />
但我对这种处理方式存疑。</p>
<h3 id="重复的command"><a class="header" href="#重复的command">重复的command</a></h3>
<p>另外一个细节是，存在server已经执行过command，但是client没有收到回复，重复发送command的情况。<br />
根据论文里所提到的，raft算法不能很好的地避免这个问题。<br />
它给出的解决方案是，client给每一个command一个序列号。但是6.824的测试框架中，command是一个interface类型，并没有序列号一说。</p>
<p>我们在做lab的时候可以不去实现&quot;client给每一个command一个序列号&quot;这个逻辑，最终也可以通过测试。</p>
<h3 id="选举定时与心跳周期的参数设置"><a class="header" href="#选举定时与心跳周期的参数设置">选举定时与心跳周期的参数设置</a></h3>
<p>如果参数设置的不好，可能会出现平分选票的情况。</p>
<p>不过如果实现逻辑没问题的话，在一个定性的区间内设置就行，不需要太考究参数的值究竟是多少，保证选举定时器的timeout是发送心跳包的周期2～3倍即可。</p>
<h3 id="死锁问题"><a class="header" href="#死锁问题">死锁问题</a></h3>
<p>写lab3时遇到的，KvServer里的线程在等Raft里的线程释放rf.mu，而Raft里的线程在等待KvServer里的线程释放kv.mu，造成了循环等待。<br />
参考了lab2的测试代码，发现这两个锁可以相互独立地获取，不必耦合在一起。</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="Raft16.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="Raft18.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="Raft16.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="Raft18.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script type="text/javascript">
            window.playground_copyable = true;
        </script>


        <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="searcher.js" type="text/javascript" charset="utf-8"></script>

        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->


    </body>
</html>
